package de.fmannan.addbook.views.actions;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import de.fmannan.addbook.MyMessageRegistry;
import de.fmannan.addbook.domainmodel.Group;
import de.fmannan.addbook.domainmodel.GroupRegistrar;

/**
 * @author fmannan
 * 
 * Executes delete-requests for groups, which have been chosen from the
 * groups popup-menu.
 * 
 */
public class GroupDeleteAction implements IObjectActionDelegate {

	public GroupDeleteAction() {
		// TODO Auto-generated constructor stub
	}

	public static final String ID = "de.fmannan.addbook.views.actions.GroupDeleteAction";
	private static Logger log = Logger.getLogger(GroupDeleteAction.class);
	
	/**
	 * Memorized active part.
	 */
    private IWorkbenchPart activePart;

    /**
     * Memorized active selection.
     */
    private ISelection activeSelection;

    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        activePart = targetPart;
    }

    /**
	 * Is executed when the user chooses the option to delete a group via the
	 * groups popup menu.
	 */
    public void run(IAction action) {
        
        if ( activeSelection instanceof IStructuredSelection) {
            IStructuredSelection structuredSelection = (IStructuredSelection) activeSelection;
            Object firstSelected = structuredSelection.getFirstElement();
            
            // If the selected item is a group we attempt to delete it
            if ( firstSelected instanceof Group ) {
            	Group deletable = (Group)firstSelected;
            	
                // ask for confirmation
                boolean confirmed = MessageDialog.openConfirm(activePart.getSite().getShell(), MyMessageRegistry.DELTE_CONTACT_TEXT,MyMessageRegistry.DELTE_CONTACT_MESSAGE); //$NON-NLS-1$ 
                if ( confirmed ) {           
                    if ( deletable != null ) {
                    	// Delete the group
                        GroupRegistrar.getInstance().removeChild(deletable);
                    }                                
                }                        	
            }
        }        
    }
    
    
    public void selectionChanged(IAction action, ISelection selection) {
        activeSelection = selection;
    }
}
